import { MCPClient } from "mcp-use";
import http from "http";

const config = {
  // 添加everything到MCP Servers
  // 有关everything，请见：https://github.com/modelcontextprotocol/servers/tree/main/src/everything
  mcpServers: {
    calculator: {
      command: "npx",
      args: ["-y", "@modelcontextprotocol/server-everything"],
    },
  },
};

const client = new MCPClient(config);

/**
 * 处理HTTP请求方法。
 * @param req 
 * @param res 
 */
async function handleRequest(req, res) {
  try {
    await client.createAllSessions();

    // 获取上边配置的MCP Server：calculator
    const session = client.getSession("calculator");
    console.log(`Get session successfully`)

    // 调用MCP Server Tool：add(a: number, b: number)
    const result = await session.callTool("add", { a: 5, b: 3 });
    
    // 将调用MCP Server Tool的结果作为HTTP响应返回
    const output = result.content[0].text;
    res.writeHead(200, { "Content-Type": "text/plain" });
    res.end(`Result from MCP Server: ${output}\n`);
  } catch (error) {
    // 异常处理
    console.error(`Catch error:`, error);
    res.writeHead(500, { "Content-Type": "text/plain" });
    res.end(`Handle error: ${error}\n`);
  } finally {
    await client.closeAllSessions();
  }
}

const port = 9000;
const host = "0.0.0.0";

const server = http.createServer(handleRequest);

server.listen(port, host, () => {
  console.log(`Server running at http://${host}:${port}/`);
});
